package jstudy.gu.user;

import java.util.Map;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import jstudy.gu.kit.number.NumberKit;
import jstudy.gu.user.mapper.UserMapper;

@RequestMapping("/user")
@RestController
@ResponseBody
@Transactional
public class UserController { // spring 管理bean 的时候,. name 是默认首字母大写,其他一样
	@Autowired
	private UserMapper mapper;

	// 对于spring 底层真正认可的是 @Component
	private static final int defaultSize = 5;

// 1. 测试,没有事务
	// 2. @Transactional 使用1/0 发生异常,成功回滚
	// 3 @Transactional 对 FileNotFoundException 没有发生回滚(因为这是收检异常, springboot 默认只回滚
	// runtimeException)
	// 4 @Transactional(rollbackFor = Throwable.class) 手动声明,SpringBoot 对所有异常都回滚,成功回滚
	// 5 = 3 不回滚//
	// 6 @Transactional
	// 用默认的,但是发生异常的时候,使用TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
	
//	@ApiOperation(value="添加用户" ,notes = "添加一个用户  \n 使用 RequestBody 传参 ")
	@PutMapping("/add")
	public Object addUser(@RequestBody @Valid User user ) {
		mapper.insert(user); // 这一步执行插入
		return user;
	}

	
	//
	@GetMapping("/get/{id}")
//	@RequestMapping(value="/get/{id}",method = RequestMethod.GET)
	public Object getUserById(@PathVariable Integer id) {
		User user = mapper.selectById(id);
		return user;
	}

	@GetMapping("/getAll")
//	@RequestMapping(value = "/getAll")
	public Object getUserGT() {
		return mapper.selectByMap(null);
	}

	@RequestMapping(value = "/getPage")
	public Object page(@RequestParam Map<String, Object> param) {
		Integer page = NumberKit.IntegerOf(param.get("page"));
		Integer pageSize = NumberKit.IntegerOf(param.get("pageSize"));
		if (page == null || page < 1) {
			page = 1; // 当前页最少是1
		}
		if (pageSize == null || pageSize < 1) {
			pageSize = defaultSize;
		}
		IPage<User> ipage = new Page<>(page, pageSize);
		IPage<User> rpage = mapper.selectPage(ipage, null);
		return rpage;
	}
}
